package com.aluvfy.bank.service;
import com.aluvfy.bank.Exceptions.MonyNoEnough;
import com.aluvfy.bank.Exceptions.TransferException;
import com.aluvfy.bank.dao.AccountDao;
import com.aluvfy.bank.dao.AccountDaoImp;
import com.aluvfy.bank.pojo.Account;
import com.aluvfy.bank.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

/**
 * @author: aluvfy
 * @description:
 * @date: 2024/11/21 16:28
 */
public class AccountServiceImp implements AccountService{
    private AccountDao accountDao = new AccountDaoImp();
    @Override
    public void transfer(String fromActno, String toActno, double money) throws MonyNoEnough, TransferException {
        //添加事务控制代码，但不能保证取的是同一个sqlSession对象，因此需要ThreadLocal绑定
        SqlSession sqlSession = SqlSessionUtil.openSession();

        //1. 判断转出账户的余额是否充足
        Account fromaccount = accountDao.selectByActno(fromActno);
        if (fromaccount.getBalance() < money) {
            //2. 如果传出余额不足，提示用户
            throw new MonyNoEnough("对不起，余额不足！");
        }
        //3. 如果余额充足，更新转出账户
        //先更新内存中java对象的余额
        Account toaccount = accountDao.selectByActno(toActno);
        fromaccount.setBalance(fromaccount.getBalance() - money);
        toaccount.setBalance(toaccount.getBalance() + money);
        int count = accountDao.updateByActno(fromaccount);

        //模拟异常
        String s = null;
        s.toString();

        //4. 更新转入账户
        count += accountDao.updateByActno(toaccount);
        if (count != 2) {
            throw new TransferException("转账失败！");
        }

        sqlSession.commit();
        SqlSessionUtil.close(sqlSession);
//        sqlSession.close();
    }
}
